<?php

namespace app\admin\controller\track;

use app\common\controller\Backend;
use think\Db;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use think\exception\PDOException;
use think\exception\ValidateException;
use Exception;
/**
 * 防伪码管理
 *
 * @icon fa fa-circle-o
 */
class Code extends Backend
{

    /**
     * Code模型对象
     * @var \app\admin\model\track\Code
     */
    protected $model = null;
    protected $relationSearch = true;
    protected $noNeedRight = ['genRandomString','exportExcel'];

    public function _initialize()
    {
        parent::_initialize();
        //检测是否安装二维码插件
        $addonInfo = get_addon_info('qrcode');
        if(!$addonInfo){
            $this->error('请安装二维码生成插件');
        }
        $this->model = new \app\admin\model\track\Code;
        $batch = date('ymd', time()) .chr(rand(65, 90)). rand(10, 99);
        $code_type= [
            '0'=>'前缀+数字和字母',
            '1'=>'前缀+字母(不限大小写)',
            '2'=>'前缀+数字',
            '3'=>'前缀+字母(大写)'
        ];
        $this->view->assign('batch',$batch);
        $this->view->assign('code_type',$code_type);

    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->with(['product'=>function($query){
                    $query->withField('name,number');
                }, 'agent'=>function($query){
                    $query->withField('nickname');
                }])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            $domain = request()->domain();
            foreach ($list as &$item) {
                $item->qrcode = $domain.'/qrcode/build?text='.urlencode($domain.'/h5#/pages/index/result?code='.$item->number);
                $item->batch2 = $item->batch."-".$item->product->number."-".$item->id;
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $data = [];
                    $code_num = intval($params['num']);//生成数量
                    $code_length = intval($params['code_length']);//长度
                    $code_pre = $params['code_pre'];//前缀
                    $code_type = $params['code_type'];//类型
                    if(empty($params['batch'])){
                        $this->error('批次不能为空');
                    }else{
                        if(!preg_match("/^[A-Za-z0-9]+$/",$params['batch'])){
                            $this->error("批次不能包含中文或特殊字符!");
                        }
                    }
                    if($code_num<1){
                        $this->error('生成数量不能小于1');
                    }
                    if($code_num>10000){
                        $this->error('单次生成不能超过1W条');
                    }
                    if($code_length<8){
                        $this->error('防伪码长度不能低于8位');
                    }
                    if(empty($params['agent_id'])){
                        $agent_id = 0;
                    }else{
                        $agent_id = $params['agent_id'];
                    }
                    if(!empty($code_pre)){
                        if(!preg_match("/^[A-Za-z0-9]+$/",$code_pre)){
                            $this->error("前缀不能包含中文或特殊字符!");
                        }
                    }
                    $new_code_length = $code_length - strlen($code_pre);
                    for ($i = 1; $i <= $code_num; $i++) {
                        $data[] = [
                            'number'=>$code_pre.$this->genRandomString($new_code_length,$code_type),
                            'product_id'=>$params['product_id'],
                            'batch'=>$params['batch'],
                            'agent_id'=>$agent_id,
                        ];
                    }
                    $result = $this->model->allowField(true)->saveAll($data);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }
    /**
     * 批量编辑
     */
    public function edits()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                if(!$params['edit_where']){
                    $this->error('请选择修改条件');
                }
                if($params['edit_where'] == 1 && !$params['edit_product_id']){
                    $this->error('请选择要编辑的产品');
                }
                if($params['edit_where'] == 2 && !$params['edit_agent_id']){
                    $this->error('请选择要编辑的代理商');
                }
                if($params['edit_where'] == 3 && !$params['edit_batch']){
                    $this->error('请输入要编辑的批次');
                }
                if(empty($params['product_id']) && empty($params['agent_id']) && empty($params['batch'])){
                    $this->error('编辑后的内容必须选择或输入一条');
                }
                Db::startTrans();
                try {
                    if($params['edit_where'] == 1){
                        $where['product_id'] = $params['edit_product_id'];
                    }
                    if($params['edit_where'] == 2){
                        $where['agent_id'] = $params['edit_agent_id'];
                    }
                    if($params['edit_where'] == 3){
                        $where['batch'] = $params['edit_batch'];
                    }
                    $data = [];
                    if($params['product_id']){
                        $data['product_id'] = $params['product_id'];
                    }
                    if($params['agent_id']){
                        $data['agent_id'] = $params['agent_id'];
                    }
                    if($params['batch']){
                        $data['batch'] = $params['batch'];
                    }
                    $result = $this->model->where($where)->update($data);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }
    ///随机字符串
    public function genRandomString($len,$t=0)
    {
        $chars = array(
            "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
            "l", "m", "n", "p", "q", "r", "s", "t", "u", "v",
            "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
            "H", "I", "J", "K", "L", "M", "N", "P", "Q", "R",
            "S", "T", "U", "V", "W", "X", "Y", "Z", "0","1","2",
            "3", "4", "5", "6", "7", "8", "9"
        );

        $chars1= array(
            "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
            "l", "m", "n", "p", "q", "r", "s", "t", "u", "v",
            "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
            "H", "I", "J", "K", "L", "M", "N", "P", "Q", "R",
            "S", "T", "U", "V", "W", "X", "Y", "Z"
        );

        $chars2 = array(
            "1", "2", "0",
            "3", "4", "5", "6", "7", "8", "9"
        );
        $chars3 = array(
            "A", "B", "C", "D", "E", "F", "G", "O" ,
            "H", "I", "J", "K", "L", "M", "N", "P", "Q", "R",
            "S", "T", "U", "V", "W", "X", "Y", "Z"
        );
        $chars4 = array(
            "A", "B", "C", "D", "E", "F", "G",
            "H", "I", "J", "K", "L", "M", "N", "P", "Q", "R",
            "S", "T", "U", "V", "W", "X", "Y", "Z", "0","1","2",
            "3", "4", "5", "6", "7", "8", "9"
        );

        if($t==1){

            $charsLen = count($chars1) - 1;

            shuffle($chars1);    // 将数组打乱

            $output = "";
            for ($i=0; $i<$len; $i++)
            {
                $output .= $chars1[mt_rand(0, $charsLen)];
            }

        }elseif($t==2){

            $charsLen = count($chars2) - 1;

            shuffle($chars2);    // 将数组打乱

            $output = "";
            for ($i=0; $i<$len; $i++)
            {
                $output .= $chars2[mt_rand(0, $charsLen)];
            }

        }elseif($t==3){

            $charsLen = count($chars3) - 1;

            shuffle($chars3);    // 将数组打乱

            $output = "";
            for ($i=0; $i<$len; $i++)
            {
                $output .= $chars3[mt_rand(0, $charsLen)];
            }

        }elseif($t==4){

            $charsLen = count($chars4) - 1;

            shuffle($chars4);    // 将数组打乱

            $output = "";
            for ($i=0; $i<$len; $i++)
            {
                $output .= $chars4[mt_rand(0, $charsLen)];
            }
        }else{

            $charsLen = count($chars) - 1;

            shuffle($chars);    // 将数组打乱

            $output = "";
            for ($i=0; $i<$len; $i++)
            {
                $output .= $chars[mt_rand(0, $charsLen)];
            }
        }
        return $output;

    }

    /**
     * 防伪码导出
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function export()
    {
        set_time_limit(0);// 脚本执行时间限制
        ini_set('memory_limit', '256M');// 脚本内存限制
        if ($this->request->isPost()) {
            $ids = $this->request->post('ids');
            if(empty($ids)){
                $this->error(__('未选择数据'));
            }
            $where = $ids == 'all' ? '1=1' : ['code.id' => ['in', explode(',', $ids)]];
            $domain = request()->domain();
            $list= $this->model
                ->with(['product'=>function($query){
                    $query->withField('name,number');
                }])
                ->where($where)
                ->field('code.id,batch,code.number,find_num,product_id,agent_id,code.createtime')
                ->select();
            $expCellName = [
                'id' => 'Id',
                'batch' => '批次号（批量号-产品编码-ID）',
                'number' => '防伪码',
                'qrcode_url' => '印刷厂使用参数',
                'find_num' => '查询次数',
                'product_id' => '产品ID',
                'agent_id' => '代理商ID',
                'create_time' => '生成时间',
            ];

            foreach ($list as &$item){
                $item['qrcode_url'] = $domain.'/h5#/pages/index/result?code='.$item['number'];
                $item['create_time'] = date('Y-m-d H:i',$item['createtime']);
                $item['batch'] = $item['batch']."-".$item['product']['number']."-".$item['id'];
            }
            $this->exportExcel('防伪码-' . date('Y-m-d H:i:s'), $expCellName, $list);
        }
    }

    public function exportExcel($expTitle, $expCellName, $expTableData){
        $fileName = $expTitle;
        $cellNum = count($expCellName);
        $dataNum = count($expTableData);
        $spreadsheet = new Spreadsheet();
        $cellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ');
        $sheet = $spreadsheet->getActiveSheet(0);
        $sheet->getStyle('A1:' . $cellName[$cellNum - 1] . '1')->getFont()->setBold(true);
        $i = 0;
        foreach ($expCellName as $key => $cell) {
            $sheet->setCellValue($cellName[$i] . '1', $cell);
            $i ++;
        }
        for ($i = 0; $i < $dataNum; $i++) {
            $j = 0;
            foreach ($expCellName as $key => $cell) {
                $sheet->setCellValue($cellName[$j] . ($i + 2), $expTableData[$i][$key]);
                $j++;
            }
        }
        ob_end_clean();
        header('pragma:public');
        header('Content-type:application/vnd.ms-excel;charset=utf-8;name="' . $fileName . '.xls"');
        header("Content-Disposition:attachment;filename=$fileName.xls"); //attachment新窗口打印inline本窗口打印
        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
        $writer->save('php://output');
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


}
